from django.db import models
from django.db.models import CharField

from user.models import CustomUser


# Create your models here.



class Music(models.Model):
    Title = models.CharField(max_length=100, verbose_name='音乐名')

    cover = models.ImageField(upload_to='avatar/%Y/%m', blank=True,null=True,verbose_name='头像')
    author = models.CharField(max_length=100,verbose_name='作者名')
    audio = models.FileField(
        upload_to='music/%Y/%m',  # 目录按年月分
        blank=False,
        verbose_name='音频文件'
    )
    cleat_time = models.TimeField(auto_now=True)
    update_time = models.TimeField(auto_now_add=True)
    user = models.ManyToManyField(max_length=100, verbose_name='用户名', to=CustomUser,
                               blank=True,)

    classifys = models.ManyToManyField(to='Classify', blank=True)

    def save(self, *args, **kwargs):
        '''自动填文件大小'''
        if self.audio:
            self.size = self.audio.size
        super().save(*args, **kwargs)


class Classify(models.Model):
    title = CharField(max_length=100, verbose_name='分类')

    def __str__(self):
        return self.title


class Love(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    music = models.ForeignKey(Music, on_delete=models.CASCADE)
    liked_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # 一个用户只能喜欢同一首歌一次
        unique_together = ('user', 'music')
        ordering = ['-liked_at']          # 新的在前

    def __str__(self):
        return f'{self.user.username} ♥ {self.music.Title}'